<template>
  <view class="warpper">
    <view class="header">
      <view class="header__left">
        <view class="header__left__from" @click="choseCurrencytype('sell')">
          {{ sellCurrencyLabel || $t("order.Please-Choose") }}
          <view class="iconfont icon-xiala"></view>
        </view>
        <view class="iconfont icon-duihuan"></view>
        <view class="header__left__to" @click="choseCurrencytype('receive')">
          {{ receiveCurrencyLabel || $t("order.Please-Choose") }}
          <view class="iconfont icon-xiala"></view>
        </view>
      </view>
      <!-- 		<view class="header__right" @click="changeSort">
				<text>{{ $t('order.Exchange-rate') }}</text>
				<image :src="otherParams.isAsc == 'asc' ? sortIcon.asc : sortIcon.desc" mode="" class="my-icon"></image>
			</view> -->
      <view class="no_tab">
        <view class="tab_btos">
          <view
            class="tab_left"
            :class="{ isSelectList: tabIndex === 1 }"
            @click="changeDirection(1)"
          >
            {{ $t("newDeal.defaultCollation") }}
          </view>
          <view
            class="money-select"
            @click="changeDirection(2)"
            style="margin: 0 30rpx"
          >
            <view
              class="select-title"
              :class="{ isSelectList: tabIndex === 2 }"
              >{{ $t("newDeal.money") }}</view
            >
            <image
              src="~@/static/image/feeServices/up.png"
              alt=""
              v-if="
                otherParams.isAsc === 'asc' &&
                otherParams.orderByColumn === 'tes.stock_num'
              "
              class="select-direction"
              mode="heightFix"
            ></image>
            <image
              src="~@/static/image/feeServices/down.png"
              alt=""
              v-else-if="
                otherParams.isAsc === 'desc' &&
                otherParams.orderByColumn === 'tes.stock_num'
              "
              class="select-direction"
              mode="heightFix"
            ></image>
            <image
              src="~@/static/image/feeServices/default.png"
              alt=""
              v-else
              class="select-direction"
              mode="heightFix"
            ></image>
          </view>
          <view class="money-select" @click="changeDirection(3)">
            <view
              class="select-title"
              :class="{ isSelectList: tabIndex === 3 }"
              >{{ $t("order.Exchange-rate") }}</view
            >
            <image
              src="~@/static/image/feeServices/up.png"
              alt=""
              v-if="
                otherParams.isAsc === 'asc' &&
                otherParams.orderByColumn === 'ted.target_price'
              "
              class="select-direction"
              mode="heightFix"
            ></image>
            <image
              src="~@/static/image/feeServices/down.png"
              alt=""
              v-else-if="
                otherParams.isAsc === 'desc' &&
                otherParams.orderByColumn === 'ted.target_price'
              "
              class="select-direction"
              mode="heightFix"
            ></image>
            <image
              src="~@/static/image/feeServices/default.png"
              alt=""
              v-else
              class="select-direction"
              mode="heightFix"
            ></image>
          </view>
        </view>
      </view>
    </view>
    <scroll-view
      :scroll-top="0"
      scroll-y="true"
      class="container"
      :refresher-enabled="true"
      @refresherrefresh="refreshList"
      :refresher-triggered="refresherState"
      @scrolltolower="loadList"
    >
      <view class="container__item" v-for="(item, index) in list" :key="index">
        <view class="container__item__left">
          <view class="container__item__left__top">
            <text class="number">{{ parseFloat(item.totalStock) }}</text>
            {{ item.sourceCurrencyVo.currency }}
            <view class="iconfont icon-duihuan"></view>
            <text class="number">{{
              parseFloat(
                (
                  item.totalStock * item.exchangeDetailList[0].targetPrice
                ).toFixed(4)
              )
            }}</text>
            {{ getReceiveCurrency(item) }}
          </view>
          <view class="container__item__left__bottom">
            {{ formatTime(item.createTime) }}
          </view>
        </view>
        <view class="container__item__center">
          <view class="container__item__center__top"
            >1:{{ parseFloat(item.exchangeDetailList[0].targetPrice) }}</view
          >
          <!-- <view class="container__item__center__bottom">
						{{ $t('order.Name') }}: {{ item.userName }}
					</view> -->
        </view>
        <view class="container__item__right" @click="buyHandle(item)">
          {{ $t("user.Details") }}
        </view>
      </view>
    </scroll-view>

    <SelectPopup
      :show.sync="SelectPopupShow"
      :option="currencyOption"
      :title="$t('order.currency')"
      :value="
        currentCurrency == 'sell'
          ? otherParams.sourceCurrency
          : otherParams.targetCurrencyId
      "
      @finish="onChangeCurrency"
      v-if="SelectPopupShow"
      labelSigned="currency"
      valueSigned="id"
    ></SelectPopup>
    <ConfirmPopup
      :show.sync="confirmPopupShow"
      tipType="Exchange"
      :exchangeWorth="parseFloat(currentOrder.totalStock)"
      :exchangeRate="`1:${parseFloat(
        currentOrder.exchangeDetailList[0].targetPrice
      )}`"
      :exchangeCurrency="currentOrder.sourceCurrencyVo.currency"
      :payMoney="
        currentOrder.exchangeDetailList
          ? currentOrder.exchangeDetailList[0].targetCurrencyVo.symbol +
            currentOrder.totalStock *
              currentOrder.exchangeDetailList[0].targetPrice
          : currentOrder.totalStock
      "
      v-if="confirmPopupShow"
      @confirm="confirmPaying"
      :objValue="currentOrder"
    ></ConfirmPopup>
    <!--  -->
  </view>
</template>

<script>
import {
  getTradeList,
  getCurrencyList,
  OrderTrade,
} from "@/services/bourse.js";
import SelectPopup from "@/components/SelectPopup.vue";
import ConfirmPopup from "./components/ConfirmPopup.vue";
import { getWalletList } from "@/services/user.js";
export default {
  data() {
    return {
      tabIndex: 1,
      searchForm: {
        pageSize: 10,
        pageNum: 1,
        title: null,
        labelId: null,
        status: 1,
        orderByColumn: null,
        isAsc: null,
      },
      currencyOption: [],
      current: 0,
      SelectPopupShow: false,
      applicationLocale: "CNY",
      confirmPopupShow: false,
      formParam: {
        pageSize: 10,
        pageNum: 1,
      },
      otherParams: {
        sourceCurrency: 1,
        targetCurrencyId: 2,
        orderByColumn: "createTime",
        isAsc: "",
        status: 1,
      },
      refresherState: false,
      list: [],
      total: 0,
      currentCurrency: "sell", // receive
      sortIcon: {
        asc: require("@/static/image/bourse/asc_icon.png"),
        desc: require("@/static/image/bourse/desc_icon.png"),
      },
      // 当前购买订单信息,用户确认购买弹窗使用
      currentOrder: {},
    };
  },
  computed: {
    sellCurrencyLabel() {
      const arr = this.currencyOption?.filter(
        (t) => t.id == this.otherParams.sourceCurrency
      );
      if (arr.length > 0) {
        return arr[0].currency;
      } else {
        return "";
      }
    },
    receiveCurrencyLabel() {
      const arr = this.currencyOption?.filter(
        (t) => t.id == this.otherParams.targetCurrencyId
      );
      if (arr.length > 0) {
        return arr[0].currency;
      } else {
        return "";
      }
    },
  },
  components: {
    SelectPopup,
    ConfirmPopup,
  },
  mounted() {
    this._getCurrencyList();
  },
  methods: {
    // 切换tab标签
    changeDirection(index) {
      if (this.tabIndex != index) {
        this.otherParams.isAsc = "";
      }
      if (index == 2 || index == 3) {
        if (index == 2) {
          // tes.stock_num 金额
          this.otherParams.orderByColumn = "tes.stock_num";
        } else if (index == 3) {
          // ted.target_price汇率
          this.otherParams.orderByColumn = "ted.target_price";
        }
        if (!this.otherParams.isAsc || this.otherParams.isAsc === "desc") {
          this.otherParams.isAsc = "asc";
          console.log(this.otherParams.isAsc);
        } else if (this.otherParams.isAsc === "asc") {
          this.otherParams.isAsc = "desc";
        }
      }
      this.tabIndex = index;
      this._getTradeList();
    },

    // 获取币种
    async _getCurrencyList() {
      const { success, result } = await getWalletList();
      if (success) {
        this.currencyOption = result.rows.filter((i) => {
          return i.currencyVo.isOpen == 1;
        });
        this.currencyOption = this.currencyOption.map((it) => {
          return {
            currency: it.currencyVo.currency,
            id: it.currencyVo.id,
            ...it,
          };
        });
        this._getTradeList();
      }
    },
    // 交易单列表
    async _getTradeList() {
      const { success, result } = await getTradeList({
        tradeScene: 2,
        shelfStatus: 1,
        ...this.formParam,
        ...this.otherParams,
      });
      this.refresherState = false;
      this.total = result.total;
      if (success) {
        if (this.formParam.pageNum == 1) {
          this.list = result.rows;
        } else {
          this.list = [...this.list, ...result.rows];
        }
      }
    },
    // 触底加载新数据
    loadList() {
      if (this.list.length < this.total) {
        this.formParam.pageNum++;
        this._getTradeList();
      }
    },
    // 下拉刷新
    refreshList() {
      this.formParam.pageNum = 1;
      this.refresherState = true;
      this._getCurrencyList();
    },
    choseCurrencytype(val) {
      this.currentCurrency = val;
      this.SelectPopupShow = true;
    },
    // 修改货币
    onChangeCurrency(val) {
      // 如果来源与接受货币相同,则将另一个置空
      if (this.currentCurrency == "sell") {
        this.otherParams.sourceCurrency = val;
        if (this.otherParams.targetCurrencyId == val) {
          this.otherParams.targetCurrencyId = "";
        }
      } else if (this.currentCurrency == "receive") {
        this.otherParams.targetCurrencyId = val;
        if (this.otherParams.sourceCurrency == val) {
          this.otherParams.sourceCurrency = "";
        }
      }
      this._getCurrencyList();
    },
    // 汇率排序
    changeSort() {
      this.otherParams.isAsc == "asc"
        ? (this.otherParams.isAsc = "desc")
        : (this.otherParams.isAsc = "asc");
      this._getCurrencyList();
    },
    // 点击购买按钮回调
    buyHandle(item) {
      uni.navigateTo({
        url: "/pagesUser/rdetails/rdetails",
      });
      // this.currentOrder = item;
      // this.confirmPopupShow = true;
    },
    // 确认购买回调
    async confirmPaying(val) {
      const obj = {
        tradeId: val.tradeId,
        tradeDetailId: val.exchangeDetailList[0].id,
      };
      const { success, result } = await OrderTrade(obj);
      if (success) {
        this.confirmPopupShow = false;
        uni.showToast({
          title: "支付成功",
          duration: 2000,
          icon: "none",
        });
        this.confirmPopupShow = false;
        uni.navigateTo({
          url: "/pagesUser/bourse/paymentStatus",
        });
      }
    },
    // 提取表格中的目标货币,防止类型错乱
    getReceiveCurrency(item) {
      const arr = this.currencyOption?.filter(
        (t) => t.id == item?.exchangeDetailList[0].targetCurrencyId
      );
      if (arr.length > 0) {
        return arr[0].currency;
      } else {
        return "";
      }
    },
    // 格式化时间
    formatTime(val) {
      val = val.slice(2);
      val = val.slice(0, val.length - 3);
      return val.replace(/-/g, "/");
    },
  },
};
</script>

<style lang="scss" scoped>
.no_tab {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-top: 20rpx;
  .tab_btos {
    display: flex;
    justify-content: center;
    // align-items: center;
  }
  .tab_left {
    // position: relative;
    // width: 140rpx;
    margin-right: 20rpx;
  }
  .isSelectList {
    color: #61bdb2;
    position: relative;
  }

  .isSelectList:after {
    content: "";
    // width: 110rpx;
    width: auto;
    height: 5upx;
    background: #61bdb2;
    position: absolute;
    bottom: -15rpx;
    left: 0;
    right: 0;
    // margin: 0 auto;
  }
  .money-select {
    width: fit-content;
    display: flex;
    align-items: center;
    cursor: pointer;

    .select-title {
      font-size: 28rpx;
      font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
      font-weight: 400;
      color: #000000;
      line-height: 40rpx;
      margin-right: 10rpx;
      user-select: none;
    }

    .select-direction {
      height: 36rpx;
    }
  }
  .tab_right {
    background: #f6f6f6;
    width: 250rpx;

    height: 60rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .r_ruo {
      font-size: 28rpx;
      color: #878787;
    }
    .r_img {
      width: 32rpx;
      height: 32rpx;
      image {
        width: 32rpx;
        height: 32rpx;
      }
    }
  }
}
.warpper {
  height: 100%;
  font-size: 28rpx;
  font-weight: 400;
  font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;

  .header {
    // display: flex;
    // align-items: center;
    font-size: 28rpx;
    font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
    font-weight: 400;
    color: #000000;
    height: 150rpx;
    margin-bottom: 10rpx;

    &__left {
      display: flex;
      justify-content: center;
      flex: 1;
      overflow: hidden;
      padding-right: 30rpx;

      &__from,
      &__to {
        display: flex;
        align-items: center;
        font-size: 28rpx;

        .icon-xiala {
          color: #bfbfbf;
          font-size: 20rpx;
          margin-left: 10rpx;
        }
      }

      .icon-duihuan {
        font-size: 42rpx;
        color: #878787;
        margin: 0 48rpx;
      }
    }

    &__right {
      display: flex;
      align-items: center;
      padding-left: 30rpx;
      text-align: right;
      white-space: nowrap;
      border-left: 2rpx solid rgba(0, 0, 0, 0.05);

      .my-icon {
        width: 16rpx;
        height: 24rpx;
        // color: pink;
        margin-left: 10rpx;
      }
    }
  }

  .container {
    height: calc(100% - 150rpx);

    &__item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      height: 184rpx;
      padding: 46rpx 0;
      background: #ffffff;
      box-shadow: inset 0px -2rpx 0px 0px rgba(0, 0, 0, 0.05);
      border-bottom: 2rpx solid #f6f6f6;

      &__left,
      &__center {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 100%;
        font-size: 24rpx;
        color: #b3b3b3;

        &__top {
          color: #878787;
          line-height: 36rpx;
        }
      }

      &__left {
        &__top {
          display: flex;
          align-items: center;

          .icon-duihuan {
            font-size: 42rpx;
            color: #878787;
            margin: 0 10rpx;
          }

          .number {
            display: inline-block;
            color: #fe6600;
            font-weight: 600;
            font-size: 32rpx;
            margin-right: 10rpx;
          }
        }
      }

      &__center {
        margin-left: auto;
        padding-right: 30rpx;
        text-align: right;
      }

      &__right {
        padding: 10rpx 24rpx;
        font-size: 28rpx;
        font-weight: 500;
        color: #ffffff;
        background-color: #61bdb2;
        border-radius: 10rpx;
        white-space: nowrap;
      }
    }
  }
}
</style>
